;(function(){
  'use strict';
  angular.module('services.omdisplay.recAbnormal')
    .factory('DiffCountServer', diffCountServer)
    .factory('DCSelectorService', diffCountSelector)
    .factory('DCQueryParamService', diffCountQueryParam)
    .factory('DCViewObjService', diffCountViewObj)
    .factory('DCChartObjService', diffCountChartObj)
    .factory('DCExportObjService', diffCountExport);
  /**
   * [diffCountServer description]
   * @param  {[type]} Restangular [description]
   * @return {[type]}             [description]
   */
  function diffCountServer(Restangular){
    return {
      diffCountQuery: diffCountQuery
    };

    function diffCountQuery(param, callback){
      Restangular.all('sas/OMdisplay/reconciliationsAbnormal/differencesCount').post(param).then(callback);
    }
  }

  diffCountServer.$inject = ['Restangular'];

  function diffCountSelector(COREDATA){
    var selector = {};
    return {
      getSelector : getSelector
    };

    function getSelector(){
      selector = {
        channelCode:COREDATA.BUSINESSLINE,
        provinceCode:COREDATA.PROVINCES,
        timeType: COREDATA.TIMETYPES
      };
      return selector;
    }
  }

  diffCountSelector.$inject = ['COREDATA'];
  /**
   * [diffCountQueryParam description]
   * @param  {[type]} CoreService        [description]
   * @param  {[type]} RecAbnormalService [description]
   * @param  {[type]} DCSelectorService  [description]
   * @param  {[type]} DiffCountServer    [description]
   * @param  {[type]} DCViewObjService   [description]
   * @param  {[type]} DCChartObjService  [description]
   * @return {[type]}                    [description]
   */
  function diffCountQueryParam(CoreService, CoreLoading, RecAbnormalService, DCSelectorService, DiffCountServer, DCViewObjService, DCChartObjService){
    var param = {};
    var date = {};
    var flag = {};
    var selector = DCSelectorService.getSelector();
    return {
      getQueryParam : getQueryParam,
      getDateParam : getDateParam,
      getFlag : getFlag,
      diffCountQueryFn : diffCountQueryFn
    };

    function getQueryParam(){
      param = {
        quarter : {}
      };
      return param;
    }

    function getDateParam(){
      if(param.timeType){
        date = RecAbnormalService.initDate(param.timeType.timeTypeCode);
      }else{
        date = RecAbnormalService.initDate(selector.timeType[0].timeTypeCode);
      }
      return date;
    }

    function getFlag(){
      flag = {
        formIsFold : false,
        showTable : false,
        showChart : false
      };
      return flag;
    }

    function setQueryParam(){
      var tempParam = {};
      var format = '';
      if(param.channelCode){
        tempParam.channelCode = param.channelCode.businessLineCode;
      }else{
        tempParam.channelCode = '';
      }
      tempParam.provincial = '1';

      if(param.timeType){
        tempParam.timeType = param.timeType.timeTypeCode;
      }else{
        tempParam.timeType = selector.timeType[0].timeTypeCode;
      }
      format = RecAbnormalService.FORMATARRAY[tempParam.timeType];
      if(param.provinceCode && param.provinceCode.length >= 1){
        tempParam.provinceCode = param.provinceCode.map(function(item){return item.provinceCode;}).join(', ');
      }else{
        tempParam.provinceCode = '';
      }
      if(param.timeType){
        switch(param.timeType.timeTypeCode){
          case '4':
            tempParam.startTime = param.quarter.startTime.substr(0, 4)+'-01-01';
            tempParam.endTime = param.quarter.endTime.substr(0, 4)+'-01-01';
            tempParam.startQuarter = param.quarter.startTime.substr(4, 1);
            tempParam.endQuarter = param.quarter.endTime.substr(4, 1);
            break;
          case '5':
            tempParam.startTime = date.startTime+'-01-01';
            tempParam.endTime = date.endTime+'-01-01';
            break;
          default :
            tempParam.startTime = CoreService.dateFormat(date.startTime, format);
            tempParam.endTime = CoreService.dateFormat(date.endTime, format);
        }
      }else{
        tempParam.startTime = CoreService.dateFormat(date.startTime, format);
        tempParam.endTime = CoreService.dateFormat(date.endTime, format);
      }
      return tempParam;
    }

    function diffCountQueryFn(){
      var queryParam = {};
      var viewObj = {};
      var chartObj = {};
      if(!flag.formIsFold){
        queryParam = setQueryParam();
        CoreLoading.setState(true);
        DiffCountServer.diffCountQuery(queryParam, function(res){
          if(res.state !== '10000' || checkData(res.data)){
            flag.showTable = false;
            CoreLoading.setState(false);
            CoreService.dialog(res.state);
            return;
          }
          viewObj = DCViewObjService.setViewObj(res.data, queryParam, param);
          chartObj = DCChartObjService.setChartObj(viewObj, queryParam);
          CoreLoading.setState(false);
          flag.formIsFold = !flag.formIsFold;
          flag.showTable = true;
          flag.showChart = false;
        });
      }else{
        flag.formIsFold = !flag.formIsFold;
      }
    }

    function checkData(data){
      var isNull = true;
      if(is.not.array(data) || data.length === 0){
        return isNull;
      }
      return (isNull = false);
    }
  }

  diffCountQueryParam.$inject = ['CoreService', 'CoreLoading', 'RecAbnormalService', 'DCSelectorService',
   'DiffCountServer', 'DCViewObjService', 'DCChartObjService'];
  /**
   * [diffCountViewObj description]
   * @param  {[type]} CoreService        [description]
   * @param  {[type]} RecAbnormalService [description]
   * @param  {[type]} DCSelectorService  [description]
   * @param  {[type]} $filter            [description]
   * @return {[type]}                    [description]
   */
  function diffCountViewObj(CoreService, RecAbnormalService, DCSelectorService, $filter,PublicFn){
    var viewObj = {};

    return {
      getViewObj : getViewObj,
      setViewObj : setViewObj
    };

    function getViewObj(){
      viewObj = {
        series : {},
        businessLines : {},
        busArr : [],
        total : {name : '汇总', data : {}},
        title : '',
        duration : '',
        showType : ''
      };
      return viewObj;
    }

    function setViewObj(data, param, formParam){
      var selectedProvinces = [];
      var selectedBusinessLine = [];
      var selector = DCSelectorService.getSelector();

      viewObj.series = {};
      viewObj.businessLines = {};
      viewObj.total.data = {};
      // viewObj.duration = RecAbnormalService.getDuration(param);
      viewObj.duration = PublicFn.fmtDateTitle(param,'timeType');
      selectedProvinces = (formParam.provinceCode && formParam.provinceCode.length >=1) ? CoreService.sort(formParam.provinceCode, 'provinceCode') : selector.provinceCode;
      selectedBusinessLine = formParam.channelCode ? formParam.channelCode : selector.channelCode;

      if(is.array(selectedBusinessLine)){
        angular.forEach(selectedBusinessLine, function(item){
          viewObj.businessLines[item.businessLineCode] = item.businessLineName;
        });

        angular.forEach(selectedBusinessLine, function(item){
          viewObj.total.data[item.businessLineCode] = {
            differencesCount : 0,
            differencesRate : 0,
            fileStorageCount : 0
          };
        });
      }else{
        viewObj.businessLines[selectedBusinessLine.businessLineCode] = selectedBusinessLine.businessLineName;
        viewObj.total.data[selectedBusinessLine.businessLineCode] = {
          differencesCount : 0,
          differencesRate : 0,
          fileStorageCount : 0
        };
      }

      angular.forEach(selectedProvinces, function(item){
        viewObj.series[item.provinceCode] = {data : {}, name : item.provinceName, code : item.provinceCode, hasData : false};
        if(is.array(selectedBusinessLine)){
          angular.forEach(selectedBusinessLine, function(subItem){
            viewObj.series[item.provinceCode].data[subItem.businessLineCode] = {
              differencesCount : 0,
              differencesRate : 0,
              fileStorageCount : 0
            };
          });
        }else{
          viewObj.series[item.provinceCode].data[selectedBusinessLine.businessLineCode] = {
            differencesCount : 0,
            differencesRate : 0,
            fileStorageCount : 0
          };
        }
      });

      angular.forEach(data, function(item){
        viewObj.series[item.provinceCode].hasData = true;
        viewObj.series[item.provinceCode].data[item.channelCode] = {
          differencesCount : Number(item.differencesCount),
          differencesRate : Number(item.differencesRate),
          fileStorageCount : Number(item.fileStorageCount)
        };
        viewObj.total.data[item.channelCode].differencesCount += Number(item.differencesCount);
        viewObj.total.data[item.channelCode].fileStorageCount += Number(item.fileStorageCount);
      });
      if(is.array(selectedBusinessLine)){
        angular.forEach(selectedBusinessLine, function(item){
          viewObj.total.data[item.businessLineCode].differencesRate = viewObj.total.data[item.businessLineCode].fileStorageCount ? (viewObj.total.data[item.businessLineCode].differencesCount / viewObj.total.data[item.businessLineCode].fileStorageCount*100) : 0;
        });
      }else{
        viewObj.total.data[selectedBusinessLine.businessLineCode].differencesRate =  viewObj.total.data[selectedBusinessLine.businessLineCode].fileStorageCount ? (viewObj.total.data[selectedBusinessLine.businessLineCode].differencesCount / viewObj.total.data[selectedBusinessLine.businessLineCode].fileStorageCount*100) : 0;
      }
      return viewObj;
    }
  }

  diffCountViewObj.$inject = ['CoreService', 'RecAbnormalService', 'DCSelectorService', '$filter','PublicFn'];
  /**
   * [diffCountChartObj description]
   * @param  {[type]} $timeout           [description]
   * @param  {[type]} DCExportObjService [description]
   * @return {[type]}                    [description]
   */
  function diffCountChartObj($timeout, DCExportObjService){
    var chartObj = {};
    var options = {};

    return{
      initChartObj: initChartObj,
      setChartObj: setChartObj,
      initOptions: initOptions,
    };

    function initChartObj(){
      chartObj = {
        options : {},
        charts : {
          '天猫旗舰店': echarts.init(document.getElementById('tmallChart')),
          '银行总对总': echarts.init(document.getElementById('bankATAChart')),
          '移动商城': echarts.init(document.getElementById('cmallChart')),
          '灵犀语音': echarts.init(document.getElementById('consonanceVoice')),
          '有价卡': echarts.init(document.getElementById('valuableCard'))
        }
      };
      return chartObj;
    }

    function initOptions(){
      options = {};
      return options;
    }

    function setChartObj(viewObj, param){
      chartObj.options = setOptions(viewObj);
      chartObj.charts = setCharts(param, viewObj);
      return chartObj;
    }

    function setOptions(viewObj){
      var options = {};
      var busCodes = [];
      viewObj.busArr = [];
      angular.forEach(viewObj.businessLines, function(item, key){
        viewObj.busArr.push(item);
        busCodes.push(key);
        options[key] = new ChartOpt(viewObj.duration.replace(/_/g, ' 至 ') + item + '对账差异情况', '差异率', '{value}%', item);
        options[key].tooltip.formatter = '{b}</br>{c}%';
      });


      viewObj.showType = viewObj.busArr[0];
      viewObj.title = viewObj.duration.replace(/_/g, ' 至 ') + viewObj.busArr.join(',') + ' 对账差异情况';

      angular.forEach(busCodes, function(busCode){
        angular.forEach(viewObj.series, function(item){
          options[busCode].xAxis[0].data.push(item.name);
        });
      });

      angular.forEach(viewObj.series, function(item){
        angular.forEach(item.data, function(subItem, key){
            options[key].series[0].data.push(subItem.differencesRate);
        });
      });
      return options;
    }

    function setCharts(param, viewObj){
      angular.forEach(viewObj.businessLines, function(item, key){

        chartObj.charts[item].clear();
        chartObj.charts[item].setOption(chartObj.options[key]);
      });
      $timeout(function(){DCExportObjService.setExportObj(param, viewObj, chartObj);}, 1200);
      return chartObj.charts;
    }

    function ChartOpt(title, yAxisName, yAxisFormatter, busArr){
      this.title = { text: title ,  x:'center'};
      this.tooltip = { show: true};
      this.xAxis = [{ type: 'category',  data: [], axisLabel:{interval:0}, splitLine: {show:false}}];
      this.legend = {data:[busArr], x:'right'};
      this.yAxis = [{ type: 'value',  name: yAxisName,  axisLabel: {formatter: yAxisFormatter}}];
      this.series = [
        { name: busArr,  type: 'bar',  data: [],
          clickable: false,
          itemStyle: {
            emphasis: {
              color: 'rgba(0, 0, 0, 0)'
            }
          }
        }
      ];
      this.animation = false;
    }
  }
  /**
   * [diffCountExport description]
   * @return {[type]} [description]
   */
  function diffCountExport(){
    var exportObj = {};

    return{
      getExportObj: getExportObj,
      setExportObj: setExportObj
    };
    function getExportObj(){
      exportObj = {
        param: {},
        isPrepare: false
      };
      return exportObj;
    }

    function setExportObj(param, viewObj, chartObj){
      var tempParam = {};
      angular.copy(param, tempParam);
      tempParam.base64s = [];
      tempParam.title = viewObj.title;
      tempParam.duration = viewObj.duration;
      angular.forEach(viewObj.businessLines, function(item){
        tempParam.base64s.push(chartObj.charts[item].getDataURL().split(',')[1]);
      });
      exportObj.param = JSON.stringify(tempParam);
      exportObj.isPrepare = true;
      return exportObj;
    }
  }

  diffCountChartObj.$inject = ['$timeout', 'DCExportObjService'];

})();